/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.config;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.cache.ProtocolParameterCache;
import com.sinodata.bsm.center.message.ProbeMessenger;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.config.ProtocolParameterService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.ProtocolConstants;
import com.sinodata.bsm.common.utils.Encipher;
import com.sinodata.bsm.common.vo.ProtocolParameter;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author dongyushi
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-5-14 上午9:42:47          dongyushi        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class JmxConfigAction extends BaseAction<ProtocolParameter> {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -2423730569613866497L;

    private Long[] ids;

    private Long id;

    private ProtocolParameter entity;

    @Autowired
    private ProtocolParameterService protocolParameterService;
    @Autowired
    private ProtocolParameterCache protocolParameterCache;

    @Action("jmxconfig")
    public String common() {
        return "common";
    }

    public String add() {
        //是否刷新列表
        Struts2Utils.setRequestAttribute("isRef", Struts2Utils.getParameter("isRef"));
        if (Struts2Utils.getParameter("isResAdd") != null) { //如果该页面是从资源新增处访问
            JSONObject object = new JSONObject();
            object.element("ip", Struts2Utils.getParameter("ip"));
            object.element("resType", Struts2Utils.getParameter("resType").toLowerCase());
            Struts2Utils.setRequestAttribute("data", object);
        }
        return "add";
    }

    /**
     * 查询列表
     * @throws IOException
     */
    @Override
    public String list() throws IOException {
        String ip = request.getParameter("ip");
        String type = ProtocolConstants.TYPE_JMX;
        Condition condition = new Condition();
        Map<String, String> map = new HashMap<String, String>();
        if (ip != null && !ip.equals("")) {
            map.put("ip", "'" + ip + "'");
        }
        map.put("type", "'" + type + "'");
        condition.setWhere(map);
        //排序
        Map<String, String> orderMap = new HashMap<String, String>();
        String order = request.getParameter("sSortDir_0");
        String col = request.getParameter("mDataProp_" + request.getParameter("iSortCol_0"));
        if (!col.equals("checkbox") && !col.equals("op")) {
            orderMap.put(col, order);
        }
        Page<ProtocolParameter> page = new Page<ProtocolParameter>();
        page.setOrder(orderMap);
        page.setPageNo(Integer.valueOf(request.getParameter("iDisplayStart")) / Integer.valueOf(request.getParameter("iDisplayLength")) + 1);
        page.setPageSize(Integer.valueOf(request.getParameter("iDisplayLength")));
        Page<ProtocolParameter> aaData = protocolParameterService.findByPage(page, condition);
        JSONObject json = new JSONObject();
        json.element("iTotalRecords", page.getTotal());
        json.element("iTotalDisplayRecords", page.getTotal());
        JSONArray array = new JSONArray();
        boolean sysManager = UserFunctionValidate.sysFunctionValidate(FunctionConstants.SYSTEM_MANAGER);
        for (ProtocolParameter protocolParameter : aaData.getRows()) {
            JSONObject obj = new JSONObject();
            obj.element("checkbox", "<div align='center'><input type='checkbox' name='dt_check' id='dt_check' value='" + protocolParameter.getId() + "'></div>");
            if (sysManager) {
                obj.element("op", "<div style='width: 80px'>&nbsp;&nbsp;<a href='javascript:edit(" + protocolParameter.getId() + ");'><img src='../style/default/bsm/images/edit.gif' title='修改'></a>&nbsp;<a href='javascript:deleteOne(" + protocolParameter.getId() + ");'><img src='../style/default/bsm/images/delete.gif' title='删除'></a>&nbsp;<a href='javascript:test(" + protocolParameter.getId() + ");'><img src='../style/default/bsm/images/test.gif' title='测试'></a><div>");
            } else {
                obj.element("op", "<div style='width: 80px'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:test(" + protocolParameter.getId() + ");'><img src='../style/default/bsm/images/test.gif' title='测试'></a><div>");
            }
            obj.element("id", protocolParameter.getId());
            obj.element("ip", protocolParameter.getIp());
            obj.element("instType", protocolParameter.getInstType());
            obj.element("userName", protocolParameter.getUserName());
            obj.element("port", protocolParameter.getPort());
            obj.element("pwd", protocolParameter.getPwd());
            obj.element("maxConn", protocolParameter.getMaxConn());
            //负责人
            //            String userIds = protocolParameter.getAdministrator();
            //            String administrators = "";
            //            if (userIds != null) {
            //                String[] users = userIds.split(",");
            //                for (int i = 0; i < users.length; i++) {
            //                    if (i == users.length - 1) {
            //                        administrators += UserUtil.getInstance().getUserById(users[i].trim()).getFullName();
            //                    } else {
            //                        administrators += UserUtil.getInstance().getUserById(users[i].trim()).getFullName() + ",";
            //                    }
            //                }
            //            }
            //            obj.element("administrator", administrators);
            array.add(obj);
        }
        json.element("aaData", array);
        renderText(json.toString());
        return null;
    }

    /**
     * 新增
     * @throws IOException
     */
    @Override
    public String save() throws IOException {
        entity.setType(ProtocolConstants.TYPE_JMX);
        if (entity.getId() != null) {
            if (protocolParameterCache.get(entity.getId()) != null) {
                //判断 修改时是否修改了密码
                if (entity.getPwd() == null || entity.getPwd().equals("")) {
                    entity.setPwd(Encipher.DecodePasswd(protocolParameterService.get(entity.getId()).getPwd()));
                }
                entity.setPwd(Encipher.EncodePasswd(entity.getPwd()));
                protocolParameterService.update(entity);
                protocolParameterCache.put(entity.getId(), entity);
                //解密后通知
                ProtocolParameter protocolParameter = new ProtocolParameter();
                copyToProtocolParameter(protocolParameter, entity);
                ProbeMessenger.notifyProtocolParameterChanged("U", protocolParameter);
            } else {
                renderText("false");
                return null;
            }
        } else {
            entity.setPwd(Encipher.EncodePasswd(entity.getPwd()));
            protocolParameterService.add(entity);
            protocolParameterCache.put(entity.getId(), entity);
            //解密后通知
            ProtocolParameter protocolParameter = new ProtocolParameter();
            copyToProtocolParameter(protocolParameter, entity);
            ProbeMessenger.notifyProtocolParameterChanged("A", protocolParameter);
        }
        renderText("true");
        return null;
    }

    public String checkDeleted() {
        JSONObject ob = new JSONObject();
        if (protocolParameterCache.get(id) == null) {
            ob.element("flag", false);
        } else {
            ob.element("flag", true);
        }
        Struts2Utils.renderJson(ob.toString());
        return null;
    }

    private void copyToProtocolParameter(ProtocolParameter protocolParameter, ProtocolParameter entity) {
        protocolParameter.setId(entity.getId());
        protocolParameter.setInstName(entity.getInstName());
        protocolParameter.setInstType(entity.getInstType());
        protocolParameter.setIp(entity.getIp());
        protocolParameter.setMaxConn(entity.getMaxConn());
        protocolParameter.setPort(entity.getPort());
        protocolParameter.setPrompt(entity.getPrompt());
        protocolParameter.setProtocol(entity.getProtocol());
        protocolParameter.setType(entity.getType());
        protocolParameter.setUrl(entity.getUrl());
        protocolParameter.setUserName(entity.getUserName());
        protocolParameter.setPwd(Encipher.DecodePasswd(entity.getPwd()));
    }

    /**
     * 后台校验ip是否重复
     * @throws IOException 
     */
    public String checkIp() throws IOException {
        Condition condition = new Condition();
        Map<String, String> map = new HashMap<String, String>();
        map.put("ip", request.getParameter("ip"));
        map.put("type", ProtocolConstants.TYPE_JMX);
        condition.setWhere(map);
        int count = protocolParameterService.getTotal(condition);
        if (count == 0) {
            renderText("true");
        }

        return null;
    }

    public String valideIpPort() throws IOException {
        if (request.getParameter("isValideFlag").equals("true")) {
            Condition condition = new Condition();
            Map<String, String> map = new HashMap<String, String>();
            map.put("ip", request.getParameter("ip"));
            map.put("port", request.getParameter("port"));
            map.put("type", ProtocolConstants.TYPE_JMX);
            condition.setWhere(map);
            int count = protocolParameterService.getTotal(condition);
            if (count == 0) {
                renderText("true");
            } else {
                renderText("false");
            }
        } else {
            renderText("true");
        }
        return null;
    }

    /**
     * 修改
     * @throws IOException
     */
    public void update() throws IOException {
        //是否刷新列表
        Struts2Utils.setRequestAttribute("isRef", Struts2Utils.getParameter("isRef"));
        protocolParameterService.update(entity);
        renderText("true");
    }

    /**
     * 删除
     */
    @Override
    public String delete() {
        //缓存判断是否被删除
        for (Long id : ids) {
            if (protocolParameterCache.get(id) == null) {
                renderText("false");
                return null;
            }
        }
        protocolParameterService.delete(ids);
        for (Long id : ids) {
            protocolParameterCache.remove(id);
        }
        for (Long id : ids) {
            ProtocolParameter protocolParameter = new ProtocolParameter();
            protocolParameter.setId(id);
            ProbeMessenger.notifyProtocolParameterChanged("R", protocolParameter);
        }
        renderText("true");
        return null;
    }

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.ModelDriven#getModel()
     */
    @Override
    public ProtocolParameter getModel() {
        return entity;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#prepareModel()
     */
    @Override
    protected void prepareModel() throws Exception {
        if (id != null) {
            entity = protocolParameterService.get(id);
            if (entity == null) {
                entity = new ProtocolParameter();
            }
        } else {
            entity = new ProtocolParameter();
        }
    }

    public Long[] getIds() {
        return ids;
    }

    public void setIds(Long[] ids) {
        this.ids = ids;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#input()
     */
    @Override
    public String input() throws Exception {
        ProtocolParameter protocolParameter = protocolParameterService.get(Long.valueOf(request.getParameter("id")));
        Struts2Utils.getRequest().setAttribute("protocolParameter", protocolParameter);
        Struts2Utils.setRequestAttribute("isRef", Struts2Utils.getParameter("isRef"));
        return "update";
    }

}